const { executeAsModal } = require("photoshop").core;
const { batchPlay } = require("photoshop").action;
const { localFileSystem: fs } = require("uxp").storage;
/**
 * 这是个测试的 
 */
const kers_test = {
    kers_t_fun: () => {
        console.log("模块--kers--函数");
    },
    kers_t_string: "模块--kers",
    kers_t_number: 7,
    kers_t_Object: {
        name: "kers73",
        type: "-模块-"
    }
}
/**
 * 运行模态函数
 * @param {function} fun 目标函数 必需
 * @param {*} cmdName {"commandName":"commandName"} 进度条弹窗-{命令标识符:标题}
 */
const runModalFunction = async function (fun, cmdName = { "commandName": "commandName" }) {
    await executeAsModal(fun, cmdName);
}
/**
 * 创建令牌地址
 * @param {*} url 
 * @returns 
 */
const tokenify = async (url) => {
    return fs.createSessionToken(await fs.getEntryWithUrl("file:" + url));
}
/**
 * 通过图层id选中图层
 * @param {*} layerId 图层id
 * @returns 
 */
const selectLayer = async (layerId) => {

    const result = await batchPlay(
        [
            {
                _obj: "select",
                _target: [
                    {
                        _ref: "layer",
                        _id: layerId
                    }
                ]
            }
        ],
        {}
    );

    return result[0];
}
/**
 * 转换为智能对象
 * @param {*} docId 文档id
 * @param {*} layerId 图层id
 * 测试显示2个id都是无效的 
 * @returns 
 */
const convertToSmartObject = async () => {
    return await batchPlay([{ _obj: "newPlacedLayer" }], {});
};
/**
 * 打开智能对象
 * @param {*} layerId 图层id id是无效的
 * @returns 
 */
const openSmartObject = async () => {
    return await batchPlay([{ _obj: "placedLayerEditContents", },], {});
};
/**
 * 新建图层
 * @param {*} docId 图层id 测试显示不会根据给的对应文档的id 去生成智能对象 是针对当前激活的文档生成的
 * @returns 
 */
const makeNewLayer = async () => {
    const result = await batchPlay(
        [
            {
                _obj: "make",
                _target: [
                    {
                        _ref: "layer",

                    },
                ],
                //layerID: layerId,
            },
        ],
        {}
    );

    return result[0];
};
/**
 * 生成智能对象并打开(当前文档大小空图层智能对象)
 * @param {*} masterDocId 测试显示不会根据给的对应文档的id 去生成智能对象 是针对当前激活的文档生成的
 * @returns 
 */
const makeAndOpenSmartObject = async () => {
    // Make new layer
    const newLayer = await makeNewLayer();

    // Convert new layer to smart object
    await convertToSmartObject();

    // Open smart object
    const smartObjectDoc = await openSmartObject();

    return {
        newLayer,
        smartObjectDoc,
    };
};
/**
 * 
 * @param {number} docId  文档id  测试了下这个id是个无效的 实际关闭的是当前激活的文档
 *                        取消docId这个参数
 * @param {string} value  是否保存文档 "yes"--保存 "no"--不保存
 * @returns 
 */
const closeDocument = async (value) => {
    //const closeDocument = async (value) => {
    const result = await batchPlay(
        [
            {
                _obj: "close",
                saving: {
                    _enum: "yesNo",
                    _value: value,
                },
                //documentID: docId,
            },
        ],
        {}
    );

    return result;
};
/**
 * 保存文档
 * @param {*} filename 
 * @param {*} folder 
 * @returns 
 */
const saveDocument = async (filename, folder) => {
    // Create file
    const file = await folder.createFile(filename, {
        overwrite: true,
    });
    // Generate token
    const token = await fs.createSessionToken(file);
    const result = await batchPlay(
        [
            {
                _obj: "save",
                in: {
                    _path: token,
                    _kind: "local",
                },
                saveStage: {
                    _enum: "saveStageType",
                    _value: "saveBegin",
                },
            },
        ],
        {}
    );

    return result;
};
const updateSmartObjectLink = async () => {
    const result = await batchPlay(
        [
            {
                _obj: "placedLayerUpdateAllModified",

            },
        ],
        {}
    );

    return result;
};



const jpg = async (url) => {
    const result = await batchPlay(
        [
            {
                _obj: "save",
                as: {
                    _obj: "JPEG",
                    extendedQuality: quality,
                    matteColor: {
                        _enum: "matteColor",
                        _value: "none",
                    },
                },
                in: {
                    _path: token,
                    _kind: "local",
                },
                saveStage: {
                    _enum: "saveStageType",
                    _value: "saveBegin",
                },
            },
        ],
        {}
    );

}

const saveImage = async (filename, folder) => {
    // Create file
    const file = await folder.createFile(filename, {
        overwrite: true,
    });
    // Generate token
    const token = await fs.createSessionToken(file);
    const result = await batchPlay(
        [
            {
                _obj: "placeEvent",
                null: {
                    _path: token,
                    _kind: "local",
                },
                saveStage: {
                    _enum: "saveStageType",
                    _value: "saveBegin",
                },
            },
        ],
        {}
    );

    return result;
};
async function savePSD(doc, entry, Options) {

    await doc.saveAs.psd(doc, entry, Options);

}
async function savePNG(doc, entry, Options, asCopy) {

    await doc.saveAs.png(doc, entry, { compression: Options }, asCopy);

}
/**
 * 创建像素选区
 * 
 * 更具图层实际像素创建的选区
 */
const actualPixelsSelection = async () => {
    const result = await batchPlay(
        [
            {
                _obj: "set",
                _target: [
                    {
                        _ref: "channel",
                        _property: "selection"
                    }
                ],
                to: {
                    _ref: "channel",
                    _enum: "channel",
                    _value: "transparencyEnum"
                },
                _options: {
                    dialogOptions: "dontDisplay"
                }
            }
        ],
        {}
    );
}
/**
 * 获取选区的边界信息
 * 
 * 直接用 doc.selection.bounds 的边界信息带有前下滑线: _left 
 * 有些地方传输的数据有这个下划线会有问题
 * @param {*} doc 当前文档
 * @returns 返回一个新的选区的边界信息
 * 
 */
const getBounds = (doc) => {
    let bounds = doc.selection.bounds;
    let newBounds = {
        left: bounds.left,
        top: bounds.top,
        bottom: bounds.bottom,
        right: bounds.right
    }
    return newBounds;
}
const cropDocument = async (doc) => {
    let bounds = k.getBounds(doc);
    await doc.crop(bounds);
}

/**
 * batchPlay 动作描述
 * {
 *      _obj: "placedLayerUpdateAllModified",  带前下划线的是有用的
 *      documentID: id,  这种不带下滑线的感觉都是无用的
 *      layerIDs: [layerId],
 * }
 */

module.exports = {
    kers_test,
    runModalFunction,
    tokenify,
    selectLayer,
    makeAndOpenSmartObject,
    makeNewLayer,
    openSmartObject,
    convertToSmartObject,
    closeDocument,
    saveDocument,
    updateSmartObjectLink,
    saveImage,
    actualPixelsSelection,
    getBounds,
    cropDocument
}